package com.trade.system.sysrun;


import com.trade.module.base.entity.Dictionary;
import com.trade.module.base.service.DictionaryService;
import com.trade.common.utils.ApplicationContextUtil;
import com.trade.common.utils.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Class Description:字典缓存工具类
 *
 * @Version v1.0 2017/4/24 22:53
 * @JDK version 1.8.0_51
 * @Author zfb
 */
public class DictionaryUtil {
    /**
     * 线程最安全的单例模式
     *
     private Singleton(){}
     public static Singleton getInstance(){
        return SingletonInstance.instance;
     }
     private static class SingletonInstance{
        static Singleton instance = new Singleton();
     }
     */
    private DictionaryUtil(){}
    public static DictionaryUtil getInstance(){
        return DictionaryUtilInstance.instance;
    }
    private static class DictionaryUtilInstance{
        static DictionaryUtil instance = new DictionaryUtil();
    }

    private static Map<String,List<Dictionary>> dictionaryMap = null;

    /**
     * 将字典初始化到内存中
     * creator: zfb @ 2017-7-16
     */
    public void initDicToMemory(){
        dictionaryMap = new HashMap<>();
        DictionaryService dictionaryService = ApplicationContextUtil.getBean("dictionaryServiceImpl");
        List<Dictionary> dicList = dictionaryService.findDictionaryAll();
        if(null!=dicList){
            //将以及字典放在map中，用id做key方便后续根据id获取
            Map<String,Dictionary> level1Map = new HashMap<>();
            for(Dictionary dic : dicList){
                if(Constants.DIC_LEVEL_1.equals(dic.getDicLevel())){
                    level1Map.put(dic.getId(),dic);
                    dictionaryMap.put(dic.getDicCode(),new ArrayList<Dictionary>());
                }
            }

            //循环遍历所有的二级字典，根据二级字典的父节点ID从一级字典的Map中获取一级字典，
            //如果获取不到则该字典已经失效，不需要添加到内存，否则添加到内存
            for(Dictionary dic:dicList){
                if(Constants.DIC_LEVEL_2.equals(dic.getDicLevel())){
                    //存在一级父节点则字典值有效
                    Dictionary level1Dic = level1Map.get(dic.getDicParentId());
                    if(null != level1Dic){
                        //从字典缓存中根据一级字典的编码获取二级字典集合，
                        //如果获取不到则该字典类型尚未添加到内存，执行添加操作，
                        //如果获取到则该字典类型已添加到内存，在该字典集合中追加二级字典
                        List<Dictionary> level2DicList = dictionaryMap.get(level1Dic.getDicCode());
                        if (null != level2DicList) {
                            level2DicList.add(dic);
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据二级字典类型获取字典值集合
     * creator: zmm @ 2016-3-16
     */
    public List<Dictionary> getDicValueListByDicTypeCode(String dicCode){
        return dictionaryMap.get(dicCode);
    }

    /**
     * 获取所有的字典值Map
     * creator: zmm @ 2016-3-16
     */
    public Map<String,List<Dictionary>> getDicMap(){
        return dictionaryMap;
    }
}
